import { UITransform } from 'cc';
import { NodeEventType } from 'cc';
import { _decorator, Component, Node } from 'cc';
const { ccclass, property, requireComponent } = _decorator;

@ccclass('ResizeComponent')
@requireComponent(UITransform)
export class ResizeComponent extends Component {

    @property(Node)
    target: Node = null!;

    start() {
        this.target.on(NodeEventType.TRANSFORM_CHANGED, this.updateTransform, this);
        this.target.on(NodeEventType.SIZE_CHANGED, this.updateSize, this);
    }

    updateTransform() {
        this.node.x = this.target.x;
        this.node.y = this.target.y;
    }

    updateSize() {
        const comp = this.node.getComponent(UITransform);
        if (!comp) return;
        const targetComp = this.target.getComponent(UITransform);
        if (!targetComp) return;
        comp.width = targetComp.width;
        comp.height = targetComp.height;
    }

    protected onDestroy(): void {
        this.target.off(NodeEventType.TRANSFORM_CHANGED, this.updateTransform, this);
        this.target.off(NodeEventType.SIZE_CHANGED, this.updateSize, this);
    }

    isUpdate = false
    protected lateUpdate(dt: number): void {
        if (this.isUpdate) return;
        this.isUpdate = true;
        this.updateTransform();
        this.updateSize();
    }
}


